# -*- coding: utf-8 -*-

# 独立使用django model（一）
# Django Shell
# 项目根目录中打开Django Shell : python manage.py shell
# import django
# django.setup()  # 装载Django
# 调用model
# django 快速入门 数据操作 https://blog.csdn.net/u011054333/article/details/78767724

# 独立使用django model（二）
import sys
import os
import json
import requests
from django.core.files import File
from django.core.files.base import ContentFile


# 建立外部脚本链接django项目
pwd=os.path.dirname(os.path.realpath(__file__))  # 当前目录所在绝对路径
root_dir = os.path.dirname(pwd)  # 项目根目录
sys.path.append(root_dir)  # 当前目录的父级目录就是项目根目录
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rmis.settings')
# 从manage.py中copy
# sys.path.append已设置临时环境变量，可以找到rmis.settings，脚本是外部脚本，只是放在了项目当中而已
# 相关数据库配置等再settings.py文件中

import django
django.setup()  # 装载django

# 脚本正文
from good.models import Good,GoodMultimedia

# create instance
# save instance
# 把要用的图片事先存储在相应的目录下，调用相对路径存储图片

with open('good_data_from_uniqlo.txt','r+') as f:
    store = f.read()
    documents = json.loads(store)


# documents_example = [
#     {
#         'title': '女装 棉混纺宽松船领长针织衫(长袖) 415364',
#         'price_sell': '¥99.00',
#         'imgs': ['https://www.uniqlo.cn/hmall/test/u0000000004281/main/first/561/1.jpg', 'https://www.uniqlo.cn/hmall/test/u0000000004281/main/other1/480/2.jpg', 'https://www.uniqlo.cn/hmall/test/u0000000004281/main/other2/480/3.jpg', 'https://www.uniqlo.cn/hmall/test/u0000000004281/main/other3/480/4.jpg', 'https://www.uniqlo.cn/hmall/test/u0000000004281/main/other4/480/5.jpg'],
#         'code': '2019022532964'
#     }
# ]

def save_good(obj):
    good = Good()
    good.code = obj['code']
    good.title = obj['title']
    good.price_sell = int(float(obj['price_sell'][1:]))
    good.price_purchase = good.price_sell // 2
    good.save()
    save_good_imgs(good, obj['imgs'])


def save_good_imgs(good,urls):
    for index,url in enumerate(urls):
        media = GoodMultimedia()
        media.fk_good = Good.objects.get(code=good.code)
        media.type = '00'

        response = requests.get(url)
        # data = File(response.content) # response.content 二进制
        media.uri.save('{0}{1}.jpg'.format(good.code, str(index).rjust(2, '0')), ContentFile(response.content))
        media.save()


for document in documents:
    save_good(document)




# from django.contrib.auth import get_user_model
# User = get_user_model()
# users = User.objects.all()
# for user in users:
#     print(user.username)



